/* eslint-disable @typescript-eslint/no-explicit-any */
import { useUserStore } from '@/stores'
import axios, { AxiosError, type Method } from 'axios'
import { showToast } from 'vant'
import router from '@/router'
export const baseURL = '/api'
const instance = axios.create({
  //1.基础地址，超时时间
  baseURL,
  timeout: 10000
})
instance.interceptors.request.use(
  (config) => {
    //2.携带token
    const store = useUserStore()
    if (store.user?.token && config.headers) {
      config.headers.Authorization = `Bearer ${store.user.token}`
    }

    return config
  },
  (err) => {
    return Promise.reject(err)
  }
)
instance.interceptors.response.use(
  (res) => {
    //3.处理业务失败
    if (res.data.code !== 200) {
      showToast(res.data.msg || '业务失败')
      return Promise.reject(res.data)
    }
    //TODO:4.摘取核心响应数据
    return res.data
  },
  (err: AxiosError) => {
    //TODO:5.处理401错误
    if (err.response?.status === 401) {
      //清除本地信息
      const store = useUserStore()
      store.delUser()
      //跳转登录页面,携带当前登录页面的地址
      showToast('登录信息已过期')
      router.push({
        path: '/login',
        query: {
          returnUrl: router.currentRoute.value.fullPath
        }
      })
    }
    return Promise.reject(err)
  }
)
export default instance
type Data<T> = {
  code: number
  msg: string
  data: T
}
export const request = <T>(url: string, method: Method = 'get', submitData?: object) => {
  return instance<any, Data<T>>({
    url,
    method,
    [method.toLowerCase() === 'get' ? 'params' : 'data']: submitData
  })
}
